//
//  AnalyticsManager.swift
//  ScaffoldKit
//
//  Created by SuXinDe on 2018/7/28.
//  Copyright © 2018年 su xinde. All rights reserved.
//

import UIKit
import ObjectiveC

fileprivate let appId = "5b5beba4b27b0a5b980000aa"
fileprivate let appStoreChannel = "App Store"

public class AnalyticsManager: NSObject {
    static let shared = AnalyticsManager()
    
    public func setup() {
        UMConfigure.initWithAppkey(appId, channel: appStoreChannel)
        MobClick.setScenarioType(.E_UM_NORMAL)
        UIViewController.injectAOPAnalytics()
    }
}


public extension UIViewController {
    public class func injectAOPAnalytics() {
        var orig = #selector(UIViewController.viewWillAppear(_:))
        var alter = #selector(UIViewController.newViewWillAppear(_:))
        let _ = UIViewController.swizzleInstanceMethod(origSelector: orig,
                                               toAlterSelector: alter)
        
        orig = #selector(UIViewController.viewWillDisappear(_:))
        alter = #selector(UIViewController.newViewWillDisAppear(_:))
        let _ = UIViewController.swizzleInstanceMethod(origSelector: orig,
                                                       toAlterSelector: alter)
    }
    
    
    // MARK: - Method Swizzling
    
    @objc func newViewWillAppear(_ animated: Bool) {
        newViewWillAppear(animated)
        MobClick.beginLogPageView(pageAnalyticsName())
        
    }
    @objc func newViewWillDisAppear(_ animated: Bool) {
        newViewWillDisAppear(animated)
        MobClick.endLogPageView(pageAnalyticsName())
        
    }
    
    fileprivate func pageAnalyticsName() -> String {
        guard let title = self.title, title.count > 0 else {
            return NSStringFromClass(UIViewController.self)
        }
        return title
    }
}
